<template>
  <div>
    <vxe-toolbar id="contractListId" :setting="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="funcAdd">新增</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      height="700"
      :row-style="rowStyle"
      :data="tableData"
      remote-sort
      @sort-change="sortList"
    >
      <vxe-table-column>
        <vxe-table-column field="shipmentName" title="客户名称" min-width="100" sortable />
        <template v-slot:header="{ column }">
          <shipmentSelect ref="shipmentSelect"  @setCustomerCode="selectCustomerCode"/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="name" title="合同名称" min-width="100" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.name" placeholder="请输入合同名称" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column   field="startDate" title="有效期" min-width="350" :formatter="termOfValidityFormatter" />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="listQuery.validityDate"
            type="daterange"
            style="width:100%"
            range-separator="至"

            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            :picker-options="pickerOptions"
            end-placeholder="结束日期"
            @change="changeDate"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="remarks" title="备注" min-width="100" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.remarks" placeholder="请输入备注" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column title="操作" fixed="right">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="详情" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code)">
              <i class="el-icon-document" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip v-if="scope.row.groupCode == party.branchCode || branch.level == 0"   class="item" effect="dark" content="编辑" placement="top">
            <vxe-button type="text" @click="funcEdit(scope.row.code)">
              <i class="el-icon-edit" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip v-if="scope.row.groupCode == party.branchCode || branch.level == 0"   class="item" effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="funcDelete(scope.row.code)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />

    <vxe-modal v-model="modelAddFlag" title="新增" width="500" height="600" resize>
      <compAdd ref="addRef" @fatherAddMethod="fatherAdd" @fatherCancelMethod="fatherCancel" />
    </vxe-modal>
    <vxe-modal v-model="modelEditFlag" title="编辑" width="500" height="600" resize>
      <compEdit ref="editRef" @fatherEditMethod="fatherEdit" @fatherCancelMethod="fatherCancel" />
    </vxe-modal>
    <vxe-modal v-model="modelDetailFlag" title="详情" width="500" height="600" resize>
      <compDetail ref="detailRef" />
    </vxe-modal>

  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
import compAdd from './components/contractAdd.vue'
import compEdit from './components/contractEdit.vue'
import compDetail from './components/contractDetail.vue'
import shipmentSelect from '@/views/components/shipmentSelect.vue'

import request from '@/utils/request'
export default {
  name: 'ContractList',
  components: {
    compAdd,
    compEdit,
    compDetail,
    shipmentSelect
  },
  data() {
    return {
      branch: this.$store.getters.branch,
      party: this.$store.getters.party,
      message: '',
      loading: false,
      tableData: [],
      modelAddFlag: false,
      modelEditFlag: false,
      modelDetailFlag: false,
      copy: false,
      partys:[],
      listQuery: {
        code: '',
        groupCode: '',
        name: '',
        contractPath: '',
        shipmentCode:'',
        shipmentName:'',
        pageNum: 1,
        pageSize: 10,
        sortField: '',
        sortType: '',
        total: 0,
        endDate: '',
        startDate:''
      },
        //时间区间
        pickerOptions: {
            shortcuts: [
                {
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date()
                        const start = new Date()
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                        picker.$emit('pick', [start, end])
                    }
                },
                {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date()
                        const start = new Date()
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                        picker.$emit('pick', [start, end])
                    }
                },
                {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date()
                        const start = new Date()
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                        picker.$emit('pick', [start, end])
                    }
                }
            ]
        }
    }
  },
  created() {
    this.findList()
    this.findShipmentPartys()
  },
  methods: {
    // 到期提醒
    rowStyle ({ row, rowIndex }) {
      let data1 = new Date()
      data1.setTime(data1.getTime() + 3600 * 1000 * 24 * 30)
      let time1 = data1.getTime()
      let data = new Date(row.endDate)
      let time = data.getTime()
      let data2 = new Date()
      let time2 = data2.getTime()
        if (time <= time1 && time2<=time) {
          return {
            backgroundColor: '#ff6666',
            color: '#ffffff'
          }
        }
        if(time2 > time){
          return {
            backgroundColor: '#ADADAD',
            color: '#ffffff'
          }
        }

      },
    // 选择客户
    selectCustomerCode(value) {
      // this.listQuery.shipmentName = value.name
      this.listQuery.shipmentCode = value;
    },

    findShipmentPartys() {
      request({
        url: '/arpa-basic-api/party/wmsShipment',
        method: 'get',
        params: { name: this.partyName }
      }).then(response => {
        this.partys = response.data
      })
    },
    findList() {
      this.loading = true
      return new Promise(resolve => {
        request({
          url: '/ntocc-wms-api/contract',
          method: 'get',
          params: this.listQuery
        }).then(response => {
          this.tableData = response.data.records
          this.listQuery.total = response.data.total
          this.loading = false
          resolve();
        })
      })
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property
        this.listQuery.sortType = order
      } else {
        this.listQuery.sortField = ''
      }
      this.findList()
    },
    // 添加方法
    funcAdd() {
      this.modelAddFlag = true
      this.$refs.addRef.init();
    },
    // 修改方法
    funcEdit(code) {
      this.$refs.editRef.getInfo(code)
      this.modelEditFlag = true
      this.$refs.editRef.partys = this.partys

    },
    // 详情方法
    funcDetail(code) {
      this.$refs.detailRef.getInfo(code)
      this.modelDetailFlag = true
    },
    // 删除方法
    funcDelete(row) {
      this.$confirm('确认删除吗？').then(_ => {
        request({ url: `/ntocc-wms-api/contract`, method: 'delete', params: { codes: row }}).then(response => {
          this.$message({ message: response.msg, type: 'success' })
          this.findList()
        })
      }).catch(_ => {})
    },
    // 增加组件的父方法
    fatherAdd() {
      this.modelAddFlag = false
      this.findList()
    },
    // 编辑组件的父方法
    fatherEdit() {
      this.modelEditFlag = false
      this.findList()
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case 'add':
          this.modelAddFlag = false
          break
        case 'edit':
          this.modelEditFlag = false
          break
        case 'detail':
          this.modelDetailFlag = false
          break
        default:
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage
      this.listQuery.pageSize = pageSize
      this.findList()
    },
    // 底部颜色设置
/*     footerCellClassName({ $rowIndex, column, columnIndex }) {
      if (columnIndex === 0) {
        if ($rowIndex === 0) {
          return 'col-blue'
        } else {
          return 'col-red'
        }
      }
    }, */
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['pageviews', 'forecast'].includes(column.property)) {
            return XEUtils.sum(data, column.property)
          }
          return null
        })
      ]
    },
    changeDate(value) {

        if(value){
            this.listQuery.startDate = value[0];
            this.listQuery.endDate = value[1]
        }else{
            this.listQuery.startDate = '';
            this.listQuery.endDate = ''
        }
    },
    termOfValidityFormatter({ row }) {
        if(row.startDate&&row.endDate){
            return row.startDate + '至 ' + row.endDate;
        }

    }
  }
}
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
